import {
  DownOutlined,
  HomeFilled,
  LoginOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MoonOutlined,
  SunOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { useAppTheme } from '@hooks/useAppTheme'
import { useAuth } from '@hooks/useAuth'
import { API_HOST_URL } from '@services/baseApi'
import { useNavigate } from '@tanstack/react-router'
import { Button, Dropdown, Layout, Space, Switch } from 'antd'
import dayjs from 'dayjs'
import { useContext, useEffect, useState } from 'react'

const { Header } = Layout
const items = [
  {
    key: '1',
    label: '账号设置',
    disabled: true,
  },
  {
    type: 'divider',
  },
  {
    key: 'profile',
    label: '修改信息',
    icon: <UserOutlined />,
    // extra: '⌘P',
  },
  {
    key: 'logout',
    label: '退出系统',
    icon: <LoginOutlined />,
    // extra: '⌘Q',
  },
]

export default function AppHeader({ toggleCollapsed, collapsed }) {
  const navigate = useNavigate()
  const { admin, logout } = useAuth()
  const { ThemeContext } = useAppTheme()
  const { theme, toggleTheme } = useContext(ThemeContext)

  const [date, setDate] = useState(dayjs().format('YYYY-MM-DD HH:mm:ss'))
  useEffect(() => {
    const timer = setInterval(() => {
      setDate(dayjs().format('YYYY-MM-DD HH:mm:ss'))
    }, 1000)
    return () => clearInterval(timer)
  }, [])

  const eventKeys = {
    profile() {
      console.log('profile')
      navigate({ to: '/system/profile' })
    },
    logout() {
      console.log('logout')
      logout()
      navigate({ to: '/login' })
    },
  }

  const onClick = ({ key }) => eventKeys[key]?.()

  return (
    <Header style={{ padding: 0, color: 'white' }} className="flex justify-between">
      {/* 展开/收起菜单按钮 */}
      <Space className="p-4">
        <Button
          title="展开/收起菜单"
          variant="default"
          color="primary"
          onClick={toggleCollapsed}
          icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          style={{ fontSize: '14px' }}
        />
        <Button
          width={44}
          title="跳到网站"
          href={API_HOST_URL}
          target="_blank"
          variant="default"
          color="primary"
          icon={<HomeFilled />}
          style={{ fontSize: '14px' }}
        />
        <Switch
          data-slot="theme-switch"
          style={{ backgroundColor: '#1890ff' }}
          checked={theme === 'dark'}
          onChange={toggleTheme}
          checkedChildren={<SunOutlined />}
          unCheckedChildren={<MoonOutlined />}
        />
      </Space>

      {/* 时间、管理员信息 */}
      <div className="mr-8">
        <span className="mr-2 font-mono text-[12px] text-[#3FB5D7]">{date}</span>
        <Dropdown menu={{ items, onClick }}>
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              {admin?.nickname}
              <DownOutlined size={24} />
            </Space>
          </a>
        </Dropdown>
      </div>
    </Header>
  )
}
